<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <!-- 添加角色按钮 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addRolesdialogVisible=true">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 角色列表表格区域 -->
            <el-table :data="RolesList" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <!-- 通过for循环遍历一级权限 -->
                        <el-row :class="['bdbottom',i===0?'bdtop':'','vcenter']" v-for="(item,i) in scope.row.children"
                            :key="item.id">
                            <!-- 一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeTag(scope.row,item.id)">{{item.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二级,三级权限 -->
                            <el-col :span="19">
                                <!-- 通过for循环遍历二级权限  -->
                                <el-row :class="[i1===0?'':'bdtop','vcenter']" v-for="(item1,i1) in item.children"
                                    :key="item1.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeTag(scope.row,item1.id)">
                                            {{item1.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item2,i2) in item1.children" :key="item2.id"
                                            closable @close="removeTag(scope.row,item2.id)">
                                            {{item2.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                        <!-- <pre>{{scope.row}}</pre> -->
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRoles(scope.row.id)">编辑
                        </el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoles(scope.row.id)">删除
                        </el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini"
                            @click="distributeRights(scope.row)">分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 分配权限的对话框 -->
        <el-dialog title="提示" :visible.sync="RightsdialogVisible" width="50%" @close="setRightsDialog">
            <!-- 树形控件 -->
            <el-tree :data="RightsList" :props="RightsProps" show-checkbox node-key="id" :default-expand-all='true'
                :default-checked-keys="defaultNode" ref="treeRef"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="RightsdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="DialogRights">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑角色的对话框 -->
        <el-dialog title="提示" :visible.sync="editRolesDialogVisible" width="50%" @close='editRolesDialogclosed'>
            <el-form ref="editRolesFormRef" :model="rolesobj" label-width="80px">
                <el-form-item label="角色名称">
                    <el-input v-model="rolesobj.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input v-model="rolesobj.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editRolesDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRolesfunction">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 添加角色的对话框 -->
        <el-dialog title="添加角色信息" :visible.sync="addRolesdialogVisible" width="70%" @close="closeRolesDialog">
            <el-form :model="addRolesruleForm" :rules="addRolesrules" ref="addRolesruleFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRolesruleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRolesruleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addRolesdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitRoles">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                //存放角色列表数据
                RolesList: [],
                //控制分配权限对话框的显示与隐藏
                RightsdialogVisible: false,
                //存放获取的权限列表数据
                RightsList: [],
                //树形控件的属性绑定对象
                RightsProps: {
                    label: 'authName',
                    children: 'children'
                },
                //三级权限中默认选中的节点数组
                defaultNode: [],
                //将要分配权限的角色的id
                roleId: '',
                //控制编辑角色对话框的显示与隐藏
                editRolesDialogVisible: false,
                //存放获取的角色信息对象
                rolesobj: {},
                //控制添加角色对话框的显示与隐藏
                addRolesdialogVisible: false,
                //添加角色的表单数据对象
                addRolesruleForm: {
                    roleName: '',
                    roleDesc: '',

                },
                //添加角色表单的验证规则对象
                addRolesrules: {
                    roleName: [{
                        required: true,
                        message: '请输入角色名称',
                        trigger: 'blur'
                    }, ],
                    roleDesc: [{
                        required: true,
                        message: '请输入角色描述',
                        trigger: 'blur'
                    }]

                }

            }
        },
        created() {
            this.getRolesList();
        },
        methods: {
            //获取角色列表数据
            async getRolesList() {
                const {
                    data: res
                } = await this.$http.get('roles');
                console.log(res);
                if (res.meta.status !== 200) {
                    this.$message.error('获取角色列表数据失败');
                }
                this.RolesList = res.data;

            },
            //点击关闭tag标签触发的事件
            async removeTag(role, rightsId) {
                const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(error => error)
                console.log(result);
                if (result !== 'confirm') {
                    return this.$message.info('取消了删除')
                }
                const {
                    data: res
                } = await this.$http.delete(`roles/${role.id}/rights/${rightsId}`)
                console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error('删除权限失败')
                }
                role.children = res.data;
            },
            //点击分配权限按钮触发的事件
            async distributeRights(role) {
                this.roleId = role.id;
                //发起分配权限的请求
                const {
                    data: res
                } = await this.$http.get('rights/tree');
                console.log(res);
                if (res.meta.status !== 200) {
                    this.$message.error('获取权限数据失败')
                }
                this.RightsList = res.data;
                //递归获取三级节点的id
                this.getdefaultnode(role, this.defaultNode)
                this.RightsdialogVisible = true;

            },
            //递归函数,用于获取角色下所有三级权限的节点id
            getdefaultnode(node, arr) {
                //如果node节点中不包含children属性,就是三级权限节点
                if (!node.children) {
                    return arr.push(node.id)
                }
                node.children.forEach(item =>
                    this.getdefaultnode(item, arr))


            },
            //分配权限对话框的关闭，清空存放三级权限节点的数组
            setRightsDialog() {
                this.defaultNode = []
            },
            //点击分配权限对话框的确定按钮触发的事件
            async DialogRights() {
                const keys = [
                    ...this.$refs.treeRef.getCheckedKeys(),
                    ...this.$refs.treeRef.getHalfCheckedKeys()
                ]
                const idStr = keys.join(',');
                const {
                    data: res
                } = await this.$http.post(`roles/${this.roleId}/rights`, {
                    rids: idStr
                });
                console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error('分配权限失败')
                }
                this.$message.success('分配权限成功');
                this.getRolesList();
                this.RightsdialogVisible = false;
            },
            //点击角色列表的编辑按钮触发的事件
            async editRoles(id) {
                const {
                    data: res
                } = await this.$http.get('roles/' + id);
                console.log(res, "222");
                if (res.meta.status !== 200) {
                    return this.$message.error('获取角色信息失败')
                }
                this.rolesobj = res.data;
                console.log(this.rolesobj, "1414");

                this.editRolesDialogVisible = true

            },
            //编辑角色的对话框关闭，重置表单
            editRolesDialogclosed() {
                this.$refs.editRolesFormRef.resetFields();
            },
            //点击确定按钮，提交修改的角色表单数据
            editRolesfunction() {
                this.$refs.editRolesFormRef.validate(async valid => {
                    if (!valid) return;
                    const {
                        data: res
                    } = await this.$http.put('roles/' + this.rolesobj.roleId, {
                        roleName: this.rolesobj.roleName,
                        roleDesc: this.rolesobj.roleDesc
                    })
                    console.log(res, "13131313");
                    if (res.meta.status !== 200) {
                        this.$message.error('修改角色信息失败')
                    }
                    this.editRolesDialogVisible = false;
                    this.getRolesList();
                    this.$message.success('修改角色信息成功')
                })
            },
            //点击角色列表的删除按钮触发的事件
            async deleteRoles(id) {
                const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(error => {
                    return error
                })
                console.log(result, "44444");
                if (result !== 'confirm') {
                    return this.$message.info('用户取消了删除')
                }
                //删除角色,发起请求
                const {
                    data: res
                } = await this.$http.delete('roles/' + id);
                console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error('删除角色失败')
                }
                this.$message.success('删除角色成功');
                this.getRolesList();

            },
            //点击添加角色对话框的确定按钮
            submitRoles() {
                this.$refs.addRolesruleFormRef.validate(async valid => {
                    console.log(valid);
                    if (!valid) return;
                    //发起添加角色的请求
                    const {
                        data: res
                    } = await this.$http.post('roles', this.addRolesruleForm);
                    console.log(res);
                    if (res.meta.status !== 201) {
                        return this.$message.error('添加角色失败')
                    }
                    this.$message.success('添加角色成功');
                    this.addRolesdialogVisible = false;
                    this.getRolesList();
                })
            },
            //关闭添加角色的对话框，清空添加角色的表单
            closeRolesDialog() {
                this.addRolesruleForm = {};
            }








        }

    }
</script>
<style lang="less" scoped>
    .el-tag {
        margin: 7px;
    }

    .bdtop {
        border-top: 1px solid #eee;
    }

    .bdbottom {
        border-bottom: 1px solid #eee;
    }

    .vcenter {
        display: flex;
        align-items: center;
    }
</style>